<?php
namespace app\handler\wechat\ai;

use app\facade\Ai;
use EasyWeChat\Kernel\Contracts\EventHandlerInterface;
use EasyWeChat\Kernel\Messages\Image;
use EasyWeChat\Kernel\Messages\Text;
use think\facade\Log;

class ImageMessageHandler implements  EventHandlerInterface
{
    use BaseMessageHandler;

    public function handle($message = null)
    {
        $wechat = $this->getApp();
        $mediaId = $message['MediaId'] ?? '';
        $openid = $message['FromUserName'] ?? '';
        $event = $message['MsgType'] ?? '';

        if ($wechat && $mediaId) {
            try {
                $wechat->customer_service
                    ->message(new Text('已接收图片，正在处理中...'))
                    ->to($openid)
                    ->send();

                $stream = $wechat->media->get($mediaId);
                if ($stream && ! is_array($stream)) {
                    //调AI人脸融合接口 随机模板
                    $res = Ai::faceSticker([
                        'image' => base64_encode($stream->getBodyContents()),
                        'sticker' => rand(1, 31),
                    ]);
                    if ($res && is_array($res) && ! $res['ret']) {
                        //保存到本地
                        $filePath = $this->getMediaPath($mediaId, $event);
                        if (file_put_contents($filePath, base64_decode($res['data']['image']))) {

                            //再调微信接口上传临时素材取media_id
                            $upload = $wechat->media->uploadImage($filePath);

                            if ($upload && $upload['media_id'] ?? null) {
                                //调用客服消息接口发送图片
                                $result = $wechat->customer_service
                                    ->message(new Image($upload['media_id']))
                                    ->to($openid)
                                    ->send();

                                if ($result && $result['errcode']) { //失败处理
                                    $wechat->customer_service
                                        ->message(new Text('手滑了一下，请重试'))
                                        ->to($openid)
                                        ->send();
                                }
                                return null;
                            }
                        }
                    }
                    $wechat->customer_service
                        ->message(new Text('合并失败，图太大(500k内)或人脸不清晰，请重试！'))
                        ->to($openid)
                        ->send();
                }
            } catch (\Exception $e) {
                $wechat->customer_service
                    ->message(new Text('接口调用失败，请稍后再试'))
                    ->to($openid)
                    ->send();
            }
        }
        return '获取参数有误！';
    }
}
